<extend name="Public/base"/>

<block name="body">
	<script type="text/javascript" src="__STATIC__/uploadify/jquery.uploadify.min.js"></script>
    <link rel="stylesheet" type="text/css" href="__CSS__/goods.css" media="all">
    <div class="main-title">
        <h2>发布商品</h2>
    </div>
    <ul class="tab-nav nav">
		<li class="current" data-tab="tab1"><a href="javascript:void(0);">基础信息</a></li></li>	
	</ul>
    <form action="{:U()}" method="post" class="form-horizontal">

        <div class="form-item">
            <label class="item-label">所属分类<span class="check-tips"></span></label>
            <div class="controls">
                <select name="fpid" id="fpid">
                    <option value="{$list[0]['id']}">{$list[0]['title']}</option>
                </select>
                <select name="spid" id="spid">
                    <option value="{$list[1]['id']}">{$list[1]['title']}</option>
                </select>
                <select name="tpid" id="tpid">
                    <option value="{$list[2]['id']}">{$list[2]['title']}</option>
                </select>
            </div>
        </div>

        <div class="form-item">
            <label class="item-label">商品名称<span class="check-tips"></span></label>
            <div class="controls">
                <input type="text" class="text input-large" name="name" value="{$goodsInfo['name']}">
            </div>
        </div>

        <div class="form-item">
            <label class="item-label">商品编码<span class="check-tips"></span></label>
            <div class="controls">
                <input type="text" class="text input-large" name="num" value="{$goodsInfo['num']}">
            </div>
        </div>

        <div class="form-item">
            <label class="item-label">SEO关键字<span class="check-tips"></span></label>
            <div class="controls">
                <input type="text" class="text input-large" name="keys" value="{$goodsContent['keys']}">
            </div>
        </div>

        <div class="form-item cf">
            <label class="item-label">SEO描述<span class="check-tips"></span></label>
            <div class="controls">
                <label class="textarea input-large">
                        <textarea name="description">{$goodsContent['description']}</textarea>
                </label>
            </div>
        </div>

        <div class="form-item cf">
            <label class="item-label">商品属性<span class="check-tips">(选择分类之后有属性则会显示对应的属性)</span></label>
            <div class="controls" id="attributes">
                <?php if($attrs){ foreach($attrs as $k=>$v){?>
                <?php echo $v['title'] ;?>：
                    <select name="attribute[]">
                    <option value="">请选择</option>
                    <?php if($attrs[$k]['list']){ foreach($attrs[$k]['list'] as $key=>$val){?>
                        <option value="<?php echo $v['id'] . '-' . $v['title'] . ':' . $val;?>" <?php echo $v['flag']==$key ? 'selected="true"' : ''; ?>><?php echo $val;?></option>
                    <?php } } ?>
                    </select>
                <?php } } ?>
            </div>
        </div>

        <div class="form-item">
            <label class="item-label">价格信息</label><span class="check-tips"></span>
            <div class="controls">
                销售价：<input type="text" class="text input-small" name="price" value="{$goodsInfo['price']}">&nbsp;
                市场价：<input type="text" class="text input-small" name="market_price" value="{$goodsInfo['market_price']}">&nbsp;
                成本价：<input type="text" class="text input-small" name="cost_price" value="{$goodsInfo['cost_price']}">&nbsp;
                库存：<input type="text" class="text input-small" name="stock" value="{$goodsInfo['stock']}">&nbsp;
                重量：<input type="text" class="text input-small" name="weight" value="{$goodsInfo['weight']}">
            </div>
        </div>

        <div class="form-item">
            <label class="item-label">销售信息</label><span class="check-tips"></span>
            <div class="controls">
                销售量：<input type="text" class="text input-small" name="sales" value="{$goodsInfo['sales']}">&nbsp;
                点击量：<input type="text" class="text input-small" name="clicks" value="{$goodsInfo['clicks']}">&nbsp;
                收藏量：<input type="text" class="text input-small" name="collects" value="{$goodsInfo['collects']}">&nbsp;
            </div>
        </div>

        <div class="form-item">
            <label class="item-label">商品规格<span class="check-tips"><a href="javascript:;" id="kongsku">开启规格</a></span></label>
            <input type="hidden" value="0" name="issku" id="issku">
            <div class="controls" id="lay_sku">
                <!-- 规格 -->
                <div class="goods_specs">
                    <?php echo $specs['com'];?>
                </div>

                <!-- 规格组合 -->
                <div class="construct_specs">

                </div>
            </div>
        </div>


        <div class="form-item cf">
            <label class="item-label">商品图片<span class="check-tips">(上传正方形规格图片：500*500像素以上)</span></label>

            <volist name="imgs" id="imgInfo"  key="opic" >
                <div class="controls" style="float:left; width:125px;">
                    <!-- <input type="text" class="text input-large" name="pic" value=""> -->
                    <input type="hidden" class="text input-large" name="pic[]" id="cover_id_pic_{$opic}" value="{$imgInfo}"/>
                    <input type="file" id="upload_picture_pic_{$opic}">
                    <div class="upload-img-box">
                        <div class="upload-pre-item">
                            <?php if($imgInfo){?>
                                <img src="<?php echo $imgInfo;?>" width="120" height="120"/>
                            <?php }else{ ?>
                                <img src="/Public/home/images/u22_normal.png" width="120" height="120"/>
                            <?php }?>
                        </div>
                    </div>
                </div>
                <script type="text/javascript">
                    //上传图片
                    /* 初始化上传插件 */
                    $("#upload_picture_pic_{$opic}").uploadify({
                        "height"          : 30,
                        "swf"             : "__STATIC__/uploadify/uploadify.swf",
                        "fileObjName"     : "download",
                        "buttonText"      : "上传图片",
                        "uploader"        : "{:U('File/uploadPicture',array('session_id'=>session_id()))}",
                        "width"           : 124,
                        'removeTimeout'   : 1,
                        'fileTypeExts'    : '*.jpg; *.png; *.gif;',
                        "onUploadSuccess" : uploadPicture_{$opic},
                        'onFallback' : function() {
                            alert('未检测到兼容版本的Flash.');
                        }
                    });
                    function uploadPicture_{$opic}(file, data){
                        var data = $.parseJSON(data);
                        var src = '';
                        if(data.status){
                            src = data.url || '__ROOT__' + data.path;
                            $("#cover_id_pic_{$opic}").val(src);
                            $("#cover_id_pic_{$opic}").parent().find('.upload-img-box').html(
                                '<div class="upload-pre-item"><img src="' + src + '" width="120" height="120"/></div>'
                            );
                        } else {
                            updateAlert(data.info);
                            setTimeout(function(){
                                $('#top-alert').find('button').click();
                                $(that).removeClass('disabled').prop('disabled',false);
                            },1500);
                        }
                    }
                </script>
            </volist>
        </div>


        <div class="form-item cf">
            <label class="item-label">商品详情<span class="check-tips"></span></label>
            <div class="controls">
                <label class="textarea">
                        <textarea name="content">{$goodsContent['content']}</textarea>
                        {:hook('adminArticleEdit', array('name'=>'content','value'=>''))}
                </label>
            </div>
        </div>

        <div class="form-item cf">
            <label class="item-label">运费模板<span class="check-tips"></span></label>
            <div class="controls">
                <select name="freight" id="freight">
                    <option value="0">免运费</option>
                </select>
            </div>
        </div>


        <div class="form-item">
            <label class="item-label">显示信息</label><span class="check-tips"></span>
            <div class="controls">
                上下架状态：
                <select name="status" id="status">
                    <option value="0" <?php echo $goodsInfo['status']==0 ? 'selected="true"' : '';?>>下架</option>
                    <option value="1" <?php echo $goodsInfo['status']==1 ? 'selected="true"' : '';?>>上架</option>
                </select>

                审核状态：
                <select name="checked" id="checked">
                    <option value="0" <?php echo $goodsInfo['checked']==0 ? 'selected="true"' : '';?>>审核中</option>
                    <option value="1" <?php echo $goodsInfo['checked']==1 ? 'selected="true"' : '';?>>已审核</option>
                </select>

                手机端显示：
                <select name="isapp" id="isapp">
                    <option value="0" <?php echo $goodsInfo['isapp']==0 ? 'selected="true"' : '';?>>隐藏</option>
                    <option value="1" <?php echo $goodsInfo['isapp']==1 ? 'selected="true"' : '';?>>显示</option>
                </select>
            </div>
        </div>
        <input type="hidden" id="id" name="id" value="<?php echo $goodsInfo['id'];?>">
        <div class="form-item">
            <button class="btn submit-btn ajax-post" id="submit" type="submit" target-form="form-horizontal">确 定</button>
            <button class="btn btn-return" onclick="javascript:history.back(-1);return false;">返 回</button>
        </div>
    </form>
</block>

<block name="script">
    <script type="text/javascript">
        //规格id
        var ids = [];
        var tmp_vals = [];  //临时存储记录的属性值
        var specsName = new Object(),
            specsList = new Object();
        var specsHtml = '';


        function goodsSkuInit(){ // 编辑sku初始化
            $('.goods_specs').find('li>input[type=checkbox]').each(function(){
                var _this = $(this);
                var _parent = _this.parent();
                var pid = _this.data('pid');
                var id = _this.data('id');
                var name = _parent.find('.val_list').val();
                var pname = _this.data('pname');

                //选中状态
                var _checked = _this.prop('checked');

                if(!_checked){
                    return;
                }

                var value = {
                    id : id,
                    pid : pid,
                    name : name,
                    pname : pname
                }
                if(specsList[pid] == undefined){
                    specsList[pid] = new Array();
                }
                if(specsList[pid][id] == undefined){
                    specsList[pid][id] = new Array();
                }
                if(specsName[pid] == undefined){
                    specsName[pid] = pname;
                }
                specsList[pid][id] = value;

                // console.log(specsList);

                //由于js数组的下标都是从0开始的，所以这里进行处理 不存在的下标元素显示undefined
                var tmpSpecs = new Array();
                for(var k in ids){
                    //规格列表临时数组
                    var tmplist = new Array();

                    //将选中的规格种类凭空undfined项
                    if(specsList[ids[k]] == undefined || specsList[ids[k]].length < 1){
                        break;
                    }

                    //将选中的规格规格清空undefined项
                    for(i in specsList[ids[k]]){
                        if(specsList[ids[k]][i] == undefined || specsList[ids[k]][i].length < 1){
                            break;
                        }
                        tmplist.push(specsList[ids[k]][i]);
                    }

                    //优选中的元素则加入
                    if(tmplist.length>0){
                        tmpSpecs.push(tmplist);
                    }
                }

                // console.log(tmpSpecs);

                //计算规格所有组合
                var all_sku = new Array();
                if(tmpSpecs.length == ids.length){
                    if(tmpSpecs.length>=2){
                        for(var i=0; i<tmpSpecs.length ; i++){
                            //递归调用，获取所有属性组合
                            all_sku = constitute_sku(all_sku, tmpSpecs[i])
                        }
                    }
                }else{
                    //如果规格种类选择不全，则清空组合
                    $('.construct_specs').html('');
                }

                // console.log(tmpSpecs);
                //所有的规格类型都有选中的，则开始组合
                specsHtml = '';
                if(tmpSpecs.length == ids.length ){
                    specsHtml += '<table><tr>';
                    for(i in ids){
                        specsHtml += '<th>'+specsName[ids[i]]+'</th>';
                    }
                    specsHtml += '<th><span class="red">*</span>销售价</th><th><span class="red">*</span>市场价</th><th><span class="red">*</span>成本价</th><th><span class="red">*</span>数量</th><th>商家编码</th></tr>';

                    //调用sku构造函数
                    constructSku(all_sku);

                    specsHtml += '</table>';

                    $('.construct_specs').html(specsHtml);
                }
            })
        }

        //sku初始化
        <?php if($goodsInfo['issku'] == 1){?>
            $('#issku').val(1);
            ids = <?php echo $specs['ids'];?>;
            tmp_vals = <?php echo $specs['tmp_val']?>;
            $('#kongsku').html('关闭规格');
            $('.goods_specs').show(); 
            goodsSkuInit()  //初始化函数调用
            $('.construct_specs').show(''); 
        <?php }?>



        //选择一级分类
        $('#fpid').change(function(){
            $('#spid').html('<option value="">请选择</option>');
            $('#tpid').html('<option value="">请选择</option>');
            //属性值，规格值做对应的改变
            hidesomething();

            var pid = $(this).val();
            if(pid){
                //ajax获取子分类
                getSub('#spid', pid);
            }

        });

        //选择二级分类
        $('#spid').change(function(){
            $('#tpid').html('<option value="">请选择</option>');
            //属性值，规格值做对应的改变
            hidesomething();

            var pid = $(this).val();
            if(pid){
                //ajax获取子分类
                getSub('#tpid', pid);
            }

        });

        //选择第三分类
        $('#tpid').change(function(){
            //属性值，规格值做对应的改变
            hidesomething()

            var pid = $(this).val();
            if(pid){
                //ajax获取属性值
                $.ajax({
                    url : '{:U("Goods/getAttribute")}',
                    data : {"pid":pid},
                    dataType : 'JSON',
                    type : 'POST',
                    success : function(ret){
                        if(ret.status==1){
                            var info = ret.info;
                            var len = info.length;
                            var str = '';
                            for(i=0; i<len; i++){
                                var vattr = info[i]['attr'];
                                var vlen = vattr.length;  //属性值
                                str += info[i]['title'] + '：';
                                str += '<select name="attribute[]">';
                                str += '<option value="">请选择</option>';
                                for(j=0;j<vlen;j++){
                                    str += '<option value="' + info[i]['id'] + '-' + info[i]['title'] + ":" + vattr[j] + '">' + vattr[j] + '</option>';
                                }
                                str += '</select>';
                                str += '&nbsp;&nbsp;';
                            }
                            $('#attributes').html(str);
                        }
                    }
                });
                
            }
        });

        //隐藏规格属性
        function hidesomething(){
            $('#kongsku').html('开启规格');
            $('#issku').val(0);
            $('.goods_specs').html('');   //清空规格
            $('.construct_specs').html(''); //清空组合规格
            $('#attributes').html('');
            ids = '';
            tmp_vals = [];
            specsName = [];
            specsList = [];
            specsHtml = '';
        }

        //获取子分类ajax
        function getSub(c_id, pid){
            //ajax获取子分类
            $.ajax({
                url : '{:U("Goods/getSubCategory")}',
                data : {"pid":pid},
                dataType : 'JSON',
                type : 'POST',
                success : function(ret){
                    if(ret.status==1){
                        var info = ret.info;
                        var len = info.length;
                        var str = '<option value="">请选择</option>';
                        for(i=0; i<len; i++){
                            str += '<option value="' + info[i]['id'] + '">' + info[i]['title'] + '</option>';
                        }
                        $(c_id).html(str);
                    }
                }
            });
        }

        //开启SKU
        $('#kongsku').click(function(){
            var pid = $('#tpid').val(),
                issku = $('#issku'),
                _this = $(this);
            //判断是开启还是关闭
            if(parseInt(issku.val())==1){
                //关闭sku
                $('.goods_specs').html('');   //清空规格
                $('.construct_specs').html(''); //清空组合规格
                $('.goods_specs').hide();   //隐藏
                $('.construct_specs').hide(''); //隐藏
                issku.val('0');
                _this.html('开启规格');
                ids = '';
                tmp_vals = [];
                specsName = [];
                specsList = [];
                specsHtml = '';
                return false;
            }

            //开启规格操作
            if(pid == ''){
                alert('请选择分类');
                return false;
            }

            //获取规格
            getSpecs(pid);
        });


        //ajax获取分类规格
        function getSpecs(pid){
            $.ajax({
                url : '{:U("Goods/getSpecs")}',
                data : {pid:pid},
                type : 'post',
                dataType : 'json',
                success : function(ret){
                    if(ret.status==1){
                        ids = ret.ids;
                        $('#issku').val('1');
                        $('#kongsku').html('关闭规格');
                        $('.goods_specs').html(ret.info);
                        $('.goods_specs').show();   //清空规格
                        $('.construct_specs').show(''); //清空组合规格
                    }else{
                        alert(ret.info);
                    }
                }
            });
        }


        //选择属性
        
        $('.goods_specs').on('change', 'input[type=checkbox]', function(){
            var _this = $(this);
            var _parent = _this.parent();
            var pid = _this.data('pid');
            var id = _this.data('id');
            var name = _parent.find('.val_list').val();
            var pname = _this.data('pname');

            //选中状态
            var _checked = _this.prop('checked');

            if(!_checked){
                for(var k in specsList[pid]){
                    if(specsList[pid][k].id == id){
                        delete(specsList[pid][k]);
                        break;
                    }
                }
                _parent.removeClass('selected');
            }else{
                var value = {
                    id : id,
                    pid : pid,
                    name : name,
                    pname : pname
                }
                if(specsList[pid] == undefined){
                    specsList[pid] = new Array();
                }
                if(specsList[pid][id] == undefined){
                    specsList[pid][id] = new Array();
                }
                if(specsName[pid] == undefined){
                    specsName[pid] = pname;
                }
                specsList[pid][id] = value;
                _parent.addClass('selected');
            }

            // console.log(specsList);

            //由于js数组的下标都是从0开始的，所以这里进行处理 不存在的下标元素显示undefined
            var tmpSpecs = new Array();
            for(var k in ids){
                //规格列表临时数组
                var tmplist = new Array();

                //将选中的规格种类凭空undfined项
                if(specsList[ids[k]] == undefined || specsList[ids[k]].length < 1){
                    break;
                }

                //将选中的规格规格清空undefined项
                for(i in specsList[ids[k]]){
                    if(specsList[ids[k]][i] == undefined || specsList[ids[k]][i].length < 1){
                        break;
                    }
                    tmplist.push(specsList[ids[k]][i]);
                }

                //优选中的元素则加入
                if(tmplist.length>0){
                    tmpSpecs.push(tmplist);
                }
            }

            // console.log(tmpSpecs);

            //计算规格所有组合
            var all_sku = new Array();
            if(tmpSpecs.length == ids.length){
                if(tmpSpecs.length>=2){
                    for(var i=0; i<tmpSpecs.length ; i++){
                        //递归调用，获取所有属性组合
                        all_sku = constitute_sku(all_sku, tmpSpecs[i])
                    }
                }
            }else{
                //如果规格种类选择不全，则清空组合
                $('.construct_specs').html('');
            }

            // console.log(tmpSpecs);
            //所有的规格类型都有选中的，则开始组合
            specsHtml = '';
            if(tmpSpecs.length == ids.length ){
                specsHtml += '<table><tr>';
                for(i in ids){
                    specsHtml += '<th>'+specsName[ids[i]]+'</th>';
                }
                specsHtml += '<th><span class="red">*</span>销售价</th><th><span class="red">*</span>市场价</th><th><span class="red">*</span>成本价</th><th><span class="red">*</span>数量</th><th>商家编码</th></tr>';

                //调用sku构造函数
                constructSku(all_sku);

                specsHtml += '</table>';

                $('.construct_specs').html(specsHtml);
            }   
            
        });

        //组合属性
        function constructSku(arrs){
            for(k in arrs){
                
                var tv = arrs[k]['id'],price,market,cost,quantity;

                price =  tmp_vals[tv + 'p'] == undefined ? '' : formatPrice(tmp_vals[tv + 'p']);
                market =  tmp_vals[tv + 'm'] == undefined ? '' : formatPrice(tmp_vals[tv + 'm']);
                cost =  tmp_vals[tv + 'c'] == undefined ? '' : formatPrice(tmp_vals[tv + 'c']);
                quantity =  tmp_vals[tv + 'q'] == undefined ? '' : tmp_vals[tv + 'q'];
                member =  tmp_vals[tv + 'mb'] == undefined ? '' : tmp_vals[tv + 'mb'];

                specsHtml += '<tr>';
                specsHtml += arrs[k]['name'];
                specsHtml += '<td>' + '<input class="inputtext sku_input sku_price" type="text" value="' + price + '" name="' + tv + 'p" >' + '</td>';
                specsHtml += '<td>' + '<input class="inputtext sku_input sku_marketprice" type="text" value="' + market + '" name="' + tv + 'm" >' + '</td>';
                specsHtml += '<td>' + '<input class="inputtext sku_input sku_costprice" type="text" value="' + cost + '" name="' + tv + 'c" >' + '</td>';
                specsHtml += '<td>' + '<input class="inputtext sku_input sku_quantity" type="text" value="' + quantity + '" name="' + tv + 'q" >' + '</td>';
                specsHtml += '<td>' + '<input class="inputtext sku_input sku_number" type="text" value="' + member + '" name="' + tv + 'mb" >' + '</td>';
                specsHtml += '</tr>';
            }
        }

        //计算出所有的规格（递归调用）
        //a已经计算好的sku，b要进入计算的sku
        function constitute_sku(a,b){
            var tmp = new Array();
            if(a.length>0){
                for(k in a){
                    for(v in b){
                        var value = {
                            id : a[k]['id'] +  b[v]['pid'] + ':' + b[v]['id'] + ';',
                            name : a[k]['name'] + '<td><span class="sp_' + b[v]['pid'] + '_' + b[v]['id'] + '" data-id="' + b[v]['id'] + '">' + b[v]['name'] + '</span></td>',
                        };
                        tmp[tmp.length]=value;
                    }
                }
            }else{
                for(v in b){
                    var value = {
                            id :  b[v]['pid'] + ':' + b[v]['id'] + ';',
                            name : '<td><span class="sp_' + b[v]['pid'] + '_' + b[v]['id'] + '" data-id="' + b[v]['id'] + '">' + b[v]['name'] + '</span></td>',
                        };
                    tmp[tmp.length]=value;
                }

            }
            return tmp;
        }

        //价格处理成2位小数格式
        function formatPrice(p){ // 将价格处理为 x.xx的格式
            p = parseFloat(p);
            if(isNaN(p) || p < 0){
                p = 0;
            }
            var price = new Number(p);
            return price.toFixed(2);
        }

        //修改规格值
        $('.goods_specs').on('change', '.val_list', function(){
            var _this = $(this),
                pid = _this.data('pid'),
                id = _this.data('id'),
                val = _this.val(),
                key = 'sp_' + pid + '_' + id;

                //修改组合属性显示的值
                $('.construct_specs').find('.' + key).html(val);

                //修改选择的规格对象信息
                if(specsList[pid] != undefined){
                    for(k in specsList[pid]){
                        if(specsList[pid][k].id == id){
                            specsList[pid][k].name = val;
                        }
                    }
                }
        });

        //编辑组合属性的规格对应的值
        $('.construct_specs').on('change', '.sku_input', function(){
            var _this = $(this);
            var _name = _this.prop('name');
            tmp_vals[_name] = _this.val();
        });

        //导航高亮
        highlight_subnav('{:U('Goods/index')}');
    </script>
</block>